package application;

import java.io.File;
import java.util.HashSet;
import java.util.Set;

import java.sql.*;

import utils.config.Config;
import utils.xml.*;

import data.Business;
import fetch.paginegialle.ParserXml2Biz;


public class MainParser {
	
	
	
	public static void main(String[] args) throws Exception {
		MainParser mp = new MainParser();
		mp.parse();
	}
	
	private String CITY;
	private String STATE;
	private String BASE_DIR;
	private String OUT_DB;
	
	public MainParser() {
		Config config = new Config(this.getClass().getSimpleName()+".ser"); 
		
		CITY = (String)config.get("CITY");
		STATE = (String)config.get("STATE");
		BASE_DIR = (String)config.get("BASE_DIR");
		OUT_DB = (String)config.get("OUT_DB");
	}
	
	public void parse() {
		ParserXml2Biz p = new ParserXml2Biz(CITY,STATE);
		
		File fdir = new File(BASE_DIR);
		File[] files = fdir.listFiles();
		
		XMLFileCleaner cleaner = new XMLFileCleaner();
		for(int i=0; i<files.length;i++) {
			if(files[i].getName().endsWith(".xml")) 
				cleaner.clean(files[i]);
		}
		
		System.out.println("Cleaning completed!");
		
		Set<Business> biz = new HashSet<Business>();
		for(int i=0; i<files.length;i++) {
			if(files[i].getName().endsWith(".xml")) 
				p.xml2biz(files[i], biz);
			if(i%50==0) System.out.println(i+" out of "+files.length+" completed!");
		}
		
		Connection c = null;
		Statement s = null;
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		    c = DriverManager.getConnection(OUT_DB);
		    s = c.createStatement();	
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		for(Business b: biz) {
			String query = "INSERT INTO Business VALUES("+b.genKey()+",'"+b.name+"','"+b.address+"','"+b.city+"','"+b.state+"','"+b.category+"',GeomFromText('POINT("+b.lon+" "+b.lat+")'))";
			System.out.println(query);
			try {
				s.executeUpdate(query);
			} catch (SQLException e) {
				if(!e.toString().contains("Duplicate entry"))
					 e.printStackTrace();
			}
		}
		
		try {
			s.close();
		    c.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	    System.out.println("Done");
	}
	
	
}
